package com.example.elderlycare.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.elderlycare.controller.entity.NursingHomeRequestBody;
import com.example.elderlycare.dao.entity.NursingHome;
import com.example.elderlycare.service.NursingHomeService;
import com.example.elderlycare.service.entity.NursingHomeListResponseBody;
import com.example.elderlycare.utils.Result;
import com.example.elderlycare.utils.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/nursing_home")
public class NursingHomeController {

    @Resource
    NursingHomeService nursingHomeService;

    /**
     * 根据条件进行分页查询的接口
     *
     * @param id        养老院 id
     * @param name      养老院名称
     * @param code      养老院代号
     * @param principal 负责人
     * @param pageSize  页大小
     * @param current   当前页
     * @return NursingHomeListResponseBody
     */
    @GetMapping("/query")
    public Result<NursingHomeListResponseBody> queryNursingHome(
            @RequestParam(value = "id", required = false) String id,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "code", required = false) String code,
            @RequestParam(value = "principal", required = false) String principal,
            @RequestParam(defaultValue = "10", value = "pageSize") int pageSize,
            @RequestParam(defaultValue = "1", value = "current") int current
    ) {
        QueryWrapper<NursingHome> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null && !"".equals(id), "id", id)
                .like(name != null && !"".equals(name), "name", name)
                .like(code != null && !"".equals(code), "code", code)
                .like(principal != null && !"".equals(principal), "principal", principal);
        try {
            NursingHomeListResponseBody res = nursingHomeService.queryNursingHome(current, pageSize, queryWrapper);
            return Result.success(res);
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * 根据养老院名称查询接口（模糊查询）
     *
     * @param name 养老院名称
     * @return NursingHomeListResponseBody
     */
    @GetMapping("/find")
    public Result<NursingHomeListResponseBody> findNursingHome(
            @RequestParam(value = "name", required = false) String name) {

        try {
            QueryWrapper<NursingHome> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name", name);
            List<NursingHome> nursingHomeList = nursingHomeService.list(queryWrapper);
            long total = nursingHomeService.count(queryWrapper);
            NursingHomeListResponseBody res = NursingHomeListResponseBody.builder()
                    .total(Math.toIntExact(total))
                    .nursingHomeList(nursingHomeList)
                    .build();
            if (res != null) {
                return Result.success(res);
            } else {
                log.warn("find nursingHome error!");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 增加养老院的接口
     *
     * @param req NursingHomeRequestBody.addNursingHome
     * @return null
     */
    @PostMapping("/add")
    public Result<?> addNursingHome(@RequestBody NursingHomeRequestBody.addNursingHome req) {
        NursingHome nursingHome = NursingHome.builder()
                .name(req.getName())
                .code(req.getCode())
                .address(req.getAddress())
                .phone(req.getPhone())
                .principal(req.getPrincipal())
                .build();
        QueryWrapper<NursingHome> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code", req.getCode());
        NursingHome record = nursingHomeService.getOne(queryWrapper);
        if (record != null) {
            return Result.error(ResultEnum.CODE_EXISTED_ERROR);
        }
        try {
            boolean flag = nursingHomeService.save(nursingHome);
            if (flag) {
                return Result.success(null);
            } else {
                log.warn("add nursingHome error!");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }

    /**
     * 更新养老院信息的接口
     *
     * @param req NursingHomeRequestBody.updateNursingHome
     * @return null
     */
    @PutMapping("/update")
    public Result<?> updateNursingHome(@RequestBody NursingHomeRequestBody.updateNursingHome req) {

        try {
            NursingHome nursingHome = NursingHome.builder()
                    .id(req.getId())
                    .name(req.getName())
                    .code(req.getCode())
                    .address(req.getAddress())
                    .phone(req.getPhone())
                    .principal(req.getPrincipal())
                    .build();
            boolean flag = nursingHomeService.updateById(nursingHome);
            if (flag) {
                NursingHome record = nursingHomeService.getById(req.getId());
                return Result.success(record);
            } else {
                log.warn("update nursingHome error!");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }

    }

    /**
     * 删除养老院的接口
     *
     * @param id 养老院id
     * @return null
     */
    @DeleteMapping("/delete")
    public Result<?> deleteNursingHome(@RequestParam("id") @NotEmpty Integer id) {
        try {
            boolean flag = nursingHomeService.removeById(id);
            if (flag) {
                return Result.success(null);
            } else {
                log.warn("delete nursingHome error");
                return Result.error(ResultEnum.DEFAULT_ERROR);
            }
        } catch (Exception e) {
            log.warn("Exception", e);
            return Result.error(ResultEnum.DEFAULT_ERROR);
        }
    }
}
